package com.dmagic.cms.common.dao;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.hibernate.Criteria;
import org.hibernate.Query;
import org.hibernate.SQLQuery;
import org.hibernate.SessionFactory;
import org.hibernate.criterion.CriteriaSpecification;
import org.hibernate.criterion.Criterion;
import org.hibernate.criterion.Disjunction;
import org.hibernate.criterion.MatchMode;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Projection;
import org.hibernate.criterion.Projections;
import org.hibernate.criterion.Restrictions;
import org.hibernate.internal.CriteriaImpl;
import org.hibernate.transform.ResultTransformer;
import org.hibernate.type.StandardBasicTypes;
import org.springframework.util.Assert;

import com.dmagic.cms.common.query.PageUtil;
import com.dmagic.cms.common.query.PropertyFilter;
import com.dmagic.cms.common.query.QueryUtil;
import com.dmagic.cms.common.query.PropertyFilter.MatchType;
import com.dmagic.cms.common.util.ListUtil;
import com.dmagic.cms.common.util.StringUtil;
import com.dmagic.cms.common.util.reflection.ReflectionUtil;



/**
 * Package SpringSide extension of a Hibernate DAO generic base class extended
 * features including paging query , query by attribute filter criteria list.
 * Can use directly in the Service layer , can also be extended to the use of
 * the generic DAO subclass , see the comment of the two constructors.
 * 
 * @param <T> DAOOperation of the object type
 * @param <PK> Primary key type
 * @author songlin.li
 */
public class HibernateDao<T, PK extends Serializable> extends SimpleHibernateDao<T, PK> {
    /**
     * For the constructor of the subclass of the Dao layer to obtain the object
     * type by the generic definition of the subclass Class. eg. public class
     * UserDao extends HibernateDao<User, Long>{ }
     */
    public HibernateDao() {
        super();
    }

    /**
     * Used to omit the Dao layer , Service layer directly the the Universal
     * HibernateDao constructor . Object type defined in the constructor Class.
     * eg. HibernateDao<User, Long> userDao = new HibernateDao<User,
     * Long>(sessionFactory, User.class);
     */
    public HibernateDao(final SessionFactory sessionFactory, final Class<T> entityClass) {
        super(sessionFactory, entityClass);
    }

    // -- Page query function --//

    /**
     * get all.
     */
    public PageUtil<T> getAll(final PageUtil<T> page) {
        return findPage(page);
    }

    /**
     * query by HQL.
     * 
     * @param page.
     * @param hql.
     * @param values values Variable number of parameters, in order to bind.
     * @return Paging query results , with the list of results and all of the
     *         query input parameters.
     */
    @SuppressWarnings("unchecked")
    public PageUtil<T> findPage(final PageUtil<T> page, final String hql, final Object... values) {
        Assert.notNull(page, "page can not be null");

        Query q = createQuery(hql, values);

        if (page.isAutoCount()) {
            int totalCount = countHqlResult(hql, values);
            page.setTotalCount(totalCount);
            if (totalCount == 0) {
                return page;
            }
        }

        setPageParameterToQuery(q, page);
        List result = q.list();
        page.setResult(result);
        return page;
    }

    /**
     * query by HQL.
     * 
     * @param page.
     * @param hql.
     * @param values Named parameters, bind by name.
     * @return Paging query results , with the list of results and all of the
     *         query input parameters.
     */
    @SuppressWarnings("unchecked")
    public PageUtil<T> findPage(final PageUtil<T> page, final String hql, final Map<String, ?> values) {
        Assert.notNull(page, "page can not be null");

        Query q = createQuery(hql, values);

        if (page.isAutoCount()) {
            int totalCount = countHqlResult(hql, values);
            page.setTotalCount(totalCount);
            if (totalCount == 0) {
                return page;
            }
        }

        setPageParameterToQuery(q, page);
        List result = q.list();
        page.setResult(result);
        return page;
    }

    /**
     * query by Criteria.
     * 
     * @param page.
     * @param criterions
     * @return Paging query results. Comes with a list of results and all of the
     *         query input parameters.
     */
    @SuppressWarnings("unchecked")
    public PageUtil<T> findPage(final PageUtil<T> page, final Criterion... criterions) {
        Assert.notNull(page, "page can not be null");

        Criteria c = createCriteria(criterions);

        if (page.isAutoCount()) {
            int totalCount = countCriteriaResult(c);
            page.setTotalCount(totalCount);
            if (totalCount == 0) {
                return page;
            }
        }

        setPageParameterToCriteria(c, page);
        List<T> result = c.list();
        page.setResult(result);
        return page;
    }

    /**
     * Set the paging parameters to the Query object , the auxiliary function.
     */
    protected Query setPageParameterToQuery(final Query q, final PageUtil<?> page) {
        if (page.isNeedPagination()) {
            Assert.isTrue(page.getPageSize() > 0, "Page Size must larger than zero");
            // hibernate firstResult start with 0
            q.setFirstResult(page.getFirst() - 1);
            q.setMaxResults(page.getPageSize());
        }
        return q;
    }

    /**
     * Set the paging parameters to the Criteria object , the auxiliary
     * function.
     */
    protected Criteria setPageParameterToCriteria(final Criteria c, final PageUtil<T> page) {
        if (page.isNeedPagination()) {
            Assert.isTrue(page.getPageSize() > 0, "Page Size must larger than zero");
            // hibernate firstResult start with 0
            c.setFirstResult(page.getFirst() - 1);
            c.setMaxResults(page.getPageSize());
        }
        if (page.isOrderBySetted()) {
            String[] orderByArray = StringUtils.split(page.getOrderBy(), ',');
            String[] orderArray = StringUtils.split(page.getOrder(), ',');

            Assert.isTrue(orderByArray.length == orderArray.length,
                    "Paging multiple sort parameters in the sort field and sort direction is not equal");

            for (int i = 0; i < orderByArray.length; i++) {
                if (PageUtil.ASC.equals(orderArray[i])) {
                    c.addOrder(Order.asc(orderByArray[i]));
                } else {
                    c.addOrder(Order.desc(orderByArray[i]));
                }
            }
        }
        return c;
    }

    /**
     * Executing count query to obtain the total number of objects the HQL query
     * that can be obtained by this function can automatically handle simple hql
     * statement , the complexity of the hql query please write separately count
     * statement to query.
     */
    protected int countHqlResult(final String hql, final Object... values) {
        String countHql = prepareCountHql(hql);

        try {
            Long count = findUnique(countHql, values);
            return count.intValue();
        } catch (Exception e) {
            throw new RuntimeException("hql can't be auto count, hql is:" + countHql, e);
        }
    }

    /**
     * Executing count query to obtain the total number of objects the HQL query
     * that can be obtained by this function can automatically handle simple hql
     * statement , the complexity of the hql query please write separately count
     * statement to query .
     */
    protected int countHqlResult(final String hql, final Map<String, ?> values) {
        String countHql = prepareCountHql(hql);

        try {
            Long count = findUnique(countHql, values);
            return count.intValue();
        } catch (Exception e) {
            throw new RuntimeException("hql can't be auto count, hql is:" + countHql, e);
        }
    }

    private String prepareCountHql(String orgHql) {
        String fromHql = orgHql;
        // the select clause and order by clause will affect the count query for
        // simple exclusion.
        fromHql = "from " + StringUtils.substringAfter(fromHql, "from");
        fromHql = StringUtils.substringBefore(fromHql, "order by");

        String countHql = "select count(*) " + fromHql;
        return countHql;
    }

    /**
     * Executing count query to obtain the total number of the Criteria query
     * object can be obtained .
     */
    @SuppressWarnings("unchecked")
    protected int countCriteriaResult(final Criteria c) {
        CriteriaImpl impl = (CriteriaImpl) c;

        // get out Projection、ResultTransformer、OrderBy, after that clean Count
        Projection projection = impl.getProjection();
        ResultTransformer transformer = impl.getResultTransformer();

        List<CriteriaImpl.OrderEntry> orderEntries = null;
        try {
            orderEntries = (List) ReflectionUtil.getFieldValue(impl, "orderEntries");
            ReflectionUtil.setFieldValue(impl, "orderEntries", new ArrayList());
        } catch (Exception e) {
            logger.error("Can not throw exception:{}", e.getMessage());
        }

        // query Count
        Long totalCountObject = (Long) c.setProjection(Projections.rowCount()).uniqueResult();
        int totalCount = (totalCountObject != null) ? totalCountObject.intValue() : 0;

        // set Projection,ResultTransformer and OrderBy
        c.setProjection(projection);

        if (projection == null) {
            c.setResultTransformer(CriteriaSpecification.ROOT_ENTITY);
        }
        if (transformer != null) {
            c.setResultTransformer(transformer);
        }
        try {
            ReflectionUtil.setFieldValue(impl, "orderEntries", orderEntries);
        } catch (Exception e) {
            logger.error("Can not throw exception:{}", e.getMessage());
        }

        return totalCount;
    }

    /**
     * count record
     * 
     * @author songlin.li
     * @param sql
     * @param values
     * @return
     */
    public int countSQLResult(String sql, Object... values) {
        int recordTotal;
        int classNameIndex = sql.toLowerCase().indexOf("from");
        if (classNameIndex == -1)
            return 0;
        else {
            sql = "select count(1) as count from (" + sql + ") orgi";
        }

        SQLQuery query = createSQLQuery(sql, values);
        recordTotal = (Integer) query.addScalar("count", StandardBasicTypes.INTEGER).uniqueResult();
        logger.debug("Total: " + recordTotal);
        return recordTotal;
    }

    public SQLQuery createSQLQuery(String sql, Object... values) {
        Assert.hasText(sql, "queryString can not be null");
        SQLQuery query = getSession().createSQLQuery(sql);

        if (values != null) {
            for (int i = 0; i < values.length; i++) {
                if (values[i] != null) {
                    query.setParameter(i, values[i]);
                }
            }
        }

        logger.debug("values: " + Arrays.asList(values));
        return query;
    }

    public List<?> queryMapDataBySql(String sql, Object... values) {
        List<?> list = createSQLQuery(sql, values).setResultTransformer(Criteria.ALIAS_TO_ENTITY_MAP).list();
        logger.debug("size: " + list.size());
        return list;
    }

    /**
     * get unique result by sql, if result is empty then return null
     * 
     * @author songlin.li
     * @param sql
     * @param objs
     * @return
     */
    public T queryUniqueBySQL(String sql, Object... objs) {
        List<T> list = queryBySQL(sql, this.entityClass, objs);
        if (ListUtil.isEmpty(list)) {
            return null;
        }
        return list.get(0);
    }

    /**
     * sql query, return entity list
     * 
     * @param sql
     * @param entity
     * @return List
     * @author Songlin.Li
     */
    @SuppressWarnings("unchecked")
    public List<T> queryBySQL(String sql, Class<T> entity, Object... objs) {
        List<T> result = null;
        try {
            logger.debug("sql: " + sql);
            SQLQuery query = this.createSQLQuery(sql, objs);
            if (entity != null) {
                query.addEntity(entity);
            }
            result = query.list();
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
        return result;
    }

    @SuppressWarnings("unchecked")
    public List<T> queryPageByHql(String hql, int start, int pageSize, Object... objs) {
        List<T> list = null;
        Query query = createQuery(hql, objs);

        if (query != null) {
            if (start > 0) {
                query.setFirstResult(start);
            }
            if (pageSize > 0) {
                query.setMaxResults(pageSize);
            }
            list = query.list();
        }

        return list;
    }

    /**
     * @param sql
     * @param objs
     * @param perPageStartNum
     * @param perPageShowNum
     * @param entity
     * @return
     */
    @SuppressWarnings("unchecked")
    public List<T> queryPageBySQL(String sql, int start, int pageSize, Class<T> entity, Object... objs) {
        List<T> list = null;
        logger.debug("sql: " + sql);
        SQLQuery query = createSQLQuery(sql, objs);
        if (query != null) {
            if (start > 0) {
                query.setFirstResult(start);
            }
            if (pageSize > 0) {
                query.setMaxResults(pageSize);
            }
            if (entity != null) {
                query.addEntity(entity);
            } else {
                query.setResultTransformer(Criteria.ALIAS_TO_ENTITY_MAP);
            }

            list = query.list();
        }

        return list;
    }

    /**
     * @param queryUtil
     * @author songlin.li
     * @return
     * @throws Exception
     */
    public QueryUtil find(QueryUtil queryUtil) throws Exception {
        if (StringUtil.isBlank(queryUtil.getQueryString()) || StringUtil.isBlank(queryUtil.getQueryType())) {
            return queryUtil;
        }

        boolean isHql = queryUtil.getQueryType().equals("hql");

        Object[] values = queryUtil.getQueryValues().toArray();

        PageUtil<?> result = isHql ? findPage(queryUtil.getPageUtil(), queryUtil.getQueryString(), values)
                : findPageBySql(queryUtil.getPageUtil(), queryUtil.getQueryString(), values);

        queryUtil.setPageUtil(result);
        return queryUtil;
    }

    /**
     * Description of the method
     * 
     * @author songlin.li
     * @param pageUtil
     * @param sql
     * @param values
     * @return
     */
    public PageUtil<?> findPageBySql(PageUtil<?> pageUtil, String sql, Object... values) {
        int classNameIndex = sql.toLowerCase().indexOf("from");
        if (classNameIndex == -1)
            return null;
        Assert.notNull(pageUtil, "page can not be null");
        if (pageUtil.isAutoCount()) {
            int totalCount = countSQLResult(sql, values);
            pageUtil.setTotalCount(totalCount);
            if (totalCount == 0) {
                return pageUtil;
            }
        }
        sql += pageUtil.getOrderByString();
        Query q = createSQLQuery(sql, values);
        setPageParameterToQuery(q, pageUtil);
        List list = q.setResultTransformer(Criteria.ALIAS_TO_ENTITY_MAP).list();
        // setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP)
        // List list = q.list();
        pageUtil.setResult(list);
        return pageUtil;
    }

    // -- PropertyFilter --//
    /**
     * @description : Find the list of Entity List by propertyName
     * 
     * @author songlin.li
     * @param propertyName
     * @param value
     * @param orderBy
     * @param isAsc
     * @return
     */
    @SuppressWarnings("unchecked")
    public List<T> findBy(String propertyName, Object value, String orderBy, boolean isAsc) {
        Assert.hasText(propertyName, "propertyName Can not be null");
        Criterion criterion = Restrictions.eq(propertyName, value);
        Criteria c = createCriteria(criterion);
        c.add(criterion);

        if (isAsc) {
            c.addOrder(Order.asc(orderBy));
        } else {
            c.addOrder(Order.desc(orderBy));
        }

        return c.list();
    }

    /**
     * @description : Find the list of Entity List by propertyName and support for multiple
     * matches .
     * 
     * @param matchType matching mode,Currently supports the values ​​of
     *            PropertyFilter's MatcheType enum.
     */
    public List<T> findBy(final String propertyName, final Object value, final MatchType matchType) {
        Criterion criterion = buildCriterion(propertyName, value, matchType);
        return find(criterion);
    }

    /**
     * @description : Find a list of objects attribute to filter list of conditions.
     * @param filters
     * @return
     */
    public List<T> find(List<PropertyFilter> filters) {
        Criterion[] criterions = buildCriterionByPropertyFilter(filters);
        return find(criterions);
    }

    /**
     * @description : Find an object attribute filtering condition list page.
     * @param page
     * @param filters
     * @return
     */
    public PageUtil<T> findPage(final PageUtil<T> page, final List<PropertyFilter> filters) {
        Criterion[] criterions = buildCriterionByPropertyFilter(filters);
        return findPage(page, criterions);
    }

    /**
     * @description :Criterion, the auxiliary function created by the property condition parameters.
     * @param propertyName
     * @param propertyValue
     * @param matchType
     * @return
     */
    protected Criterion buildCriterion(final String propertyName, final Object propertyValue, final MatchType matchType) {
        Assert.hasText(propertyName, "propertyNameCan not be empty");
        Criterion criterion = null;
        // based on MatchType create criterion
        switch (matchType) {
            case EQ:
                criterion = Restrictions.eq(propertyName, propertyValue);
                break;
            case LIKE:
                criterion = Restrictions.like(propertyName, (String) propertyValue, MatchMode.ANYWHERE);
                break;

            case LE:
                criterion = Restrictions.le(propertyName, propertyValue);
                break;
            case LT:
                criterion = Restrictions.lt(propertyName, propertyValue);
                break;
            case GE:
                criterion = Restrictions.ge(propertyName, propertyValue);
                break;
            case GT:
                criterion = Restrictions.gt(propertyName, propertyValue);
        }
        return criterion;
    }

    /**
     * @description : Criterion array of auxiliary functions according to the attribute list of
     * conditions to create.
     * @param filters
     * @return
     */
    protected Criterion[] buildCriterionByPropertyFilter(final List<PropertyFilter> filters) {
        List<Criterion> criterionList = new ArrayList<Criterion>();
        for (PropertyFilter filter : filters) {
            if (!filter.hasMultiProperties()) { // Only need to compare a
                                                // property.
                Criterion criterion = buildCriterion(filter.getPropertyName(), filter.getMatchValue(),
                        filter.getMatchType());
                criterionList.add(criterion);
            } else {// Contain the need to compare multiple properties , or
                    // processing.
                Disjunction disjunction = Restrictions.disjunction();
                for (String param : filter.getPropertyNames()) {
                    Criterion criterion = buildCriterion(param, filter.getMatchValue(), filter.getMatchType());
                    disjunction.add(criterion);
                }
                criterionList.add(disjunction);
            }
        }
        return criterionList.toArray(new Criterion[criterionList.size()]);
    }
}
